# -*- coding: utf-8 -*-
from datetime import timedelta
from utils.operators.spark_sql_operator import SparkSqlOperator
from airflow.models import Variable
from spmi_analysis.tidb.tidb_dm_composite_bill_network_sign_daliy_summary_dt import tidb_dm_composite_bill_network_sign_daliy_summary_dt
from airflow.exceptions import AirflowSkipException
import pendulum

# 必须使用spark client模式，目前不能用cluster_for_spark_sql_operator
# =====================================tidb相关参数及http Feign信息 无需修改！！！===========================================

# 大数据自有tidb
bd_tidb_url = Variable.get('bigdata_tidb_url')
bd_tidb_user = Variable.get('bigdata_tidb_user')
bd_tidb_password = Variable.get('bigdata_tidb_password')
http_feign = 'http://spmreportapi-inner.jtexpress.com.cn/ylspmibillreportschedule/spmiReport/bigData/notification/'

# 所有报表+流水表都集中在 bd_tidb_url
# uat  http://demo-spmreportapi-inner.jtexpress.com.cn/ylspmibillreportschedule/spmiReport/bigData/notification/
# pro http://spmreportapi-inner.jtexpress.com.cn/ylspmibillreportschedule/spmiReport/bigData/notification/
# ======================================================================================================================

# ##################################数据质量校验相关信息（根据自身推送任务，认真填写）###########################################

#tidb任务的id与name。id、name不能重复
tidb_report_id = '1007'
tidb_report_name = '一口价日签收维度汇总'

#写入tidb临时表的库名及表名  【！！！默认核对数据质量校验 核查临时表！！！】
tidb_tmp_db = 'spmi_dm'
tidb_tmp_table = 'dm_composite_bill_network_sign_daliy_summary_dt'

#后端合并tidb正式表的库名及表名
tidb_reg_db = ''
tidb_reg_table = ''

#数据质量校验的hive表信息【！！！默认核查dt=t-1天的分区，如不符合要求自行修改sql ！！！】
hive_table = 'spmi_tmp.dm_composite_bill_network_sign_daliy_summary_dt'

########################################################################################################################


class SkippedSparkSqlOperator(SparkSqlOperator):
    def pre_execute(self, context):
        cst = pendulum.timezone('Asia/Shanghai')
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)
        schedule_date = ['25']
        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)


dqc_tidb_dm_composite_bill_network_sign_daliy_summary_dt = SparkSqlOperator(
    task_id='dqc_tidb_dm_composite_bill_network_sign_daliy_summary_dt',
    task_concurrency=1,
    pool_slots=1,
    master='yarn',
    name='dqc_tidb_dm_composite_bill_network_sign_daliy_summary_dt_{{ execution_date | date_add(1) | cst_ds }}',
    sql='spmi_analysis/dqc/dqc_tidb_dm_composite_bill_network_sign_daliy_summary_dt/execute.sql',
    retries=0,
    driver_memory='1G',
    driver_cores=1,
    executor_cores=2,
    executor_memory='4G',
    email=['shenjiaming@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    num_executors=1,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    conf={'spark.dynamicAllocation.enabled': 'true',  # 动态资源开启
          'spark.shuffle.service.enabled': 'true',  # 动态资源 Shuffle 服务开启
          'spark.dynamicAllocation.maxExecutors': 3,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 300,  # 动态资源自动释放闲置 Executor 的超时时间(s)
          'spark.sql.sources.partitionOverwriteMode': 'dynamic',  # 允许删改已存在的分区
          'spark.executor.memoryOverhead': '1G',  # 堆外内存
          },
    yarn_queue='pro',
    execution_timeout=timedelta(hours=1),
    params={'tidb_url': bd_tidb_url, 'tidb_user': bd_tidb_user,'tidb_password': bd_tidb_password,
            'http_feign' : http_feign,
            'bd_tidb_url': bd_tidb_url,'bd_tidb_user': bd_tidb_user,'bd_tidb_password': bd_tidb_password,'tidb_report_id': tidb_report_id ,'tidb_report_name': tidb_report_name ,'tidb_tmp_db': tidb_tmp_db ,'tidb_tmp_table': tidb_tmp_table ,'tidb_reg_db': tidb_reg_db ,'tidb_reg_table': tidb_reg_table ,'hive_table': hive_table}
)


dqc_tidb_dm_composite_bill_network_sign_daliy_summary_dt << tidb_dm_composite_bill_network_sign_daliy_summary_dt


